package cn.itcast.star.graph.core.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.jwt.JWT;
import cn.itcast.star.graph.core.pojo.User;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.stereotype.Component;

import javax.print.attribute.standard.NumberUp;

/**
 * @author Windows
 */
@Component
public class JWTUtils {

    static final String key = "itheima.com";

    public static String createJWT(Long id, String name) {
        return JWT.create()
                .setPayload("uid", id)
                .setPayload("uname", name)
                .setExpiresAt(DateTime.now().offsetNew(DateField.YEAR, 1))
                .setKey(key.getBytes())
                .sign();
    }

    /**
     * token校验
     *验证token
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        try{
            return JWT.of(token).setKey(key.getBytes()).verify();
        }catch (Exception e){
            return false;
        }
    }

    /**
     *获取用户信息
     * @param token
     * @return
     */
    public static User getUser(String token){
        try{
            JWT jwt = JWT.of(token).setKey(key.getBytes());
            User user = new User();
            user.setId((jwt.getPayload("uid")==null ? null :
                    NumberUtil.parseLong(jwt.getPayload("uid").toString())));
            user.setUsername(jwt.getPayload("uname").toString());
            return user;
        }catch (Exception e){
            return null;
        }
    }

}